<?php
namespace app\admin\model;
use \think\Db;
class AdminRole extends \think\Model{
    public $c;
    public $a;
    public $url;
    
    public function __construct($user_id = ''){
        $this->c        = com_controller();
        $this->a        = com_action();
        $this->url      = $this->c."/".$this->a;
    }
    
    /**
     * 验证是否有权限
     * @return 有权限 true   无权限为false;
     */
    public function checkRight(){
        $id = session("admin_user_id");
        if(!$id)
            return false;
        if( com_admininfo('role_ids')=='superman' )
            return true;
        return !in_array($this->url, $this->getDenyUrls());
    }
    
    /**
     * 取得导航
     * @return \think\mixed
     */
    public function getMenu(){
        if( session('?menu') )
            return \think\Session::get('menu');
        
        $menu = c('menu');
        if( com_admininfo('role_ids')=='superman' )
            return $menu;
        
        #去掉没有权限的链接
        $urls = $this->getDenyUrls();
        
        $temp = [];
        foreach($menu as $k => $v){
            $temp[$k] = $v;
            $temp[$k]['son'] = array_diff($v['son'],$urls);
        }
        #去掉没有子链接的，一级链接
        foreach($temp as  $k => $v){
            if(!$v['son'])
                unset($temp[$k]);
        }
        session('menu',$temp);
        return $temp;
        
    }
    
    /**
     * 取得权限数组
     * 一个人有多个部门， 每个部门都限制，才是他真正没有权限的
     */
    public function getDenyUrls(){
        if( session('?deny_urls') )
            return \think\Session::get('deny_urls');
        
        #取多个部门，限制权限的交集
        $rs = Db::name('admin_role')->field('content')->where('id','in', trim(com_admininfo('role_ids'),","))->select();
        $temp = array_filter( explode(",", $rs[0]['content']) );
        foreach($rs as $v){
            $temp = array_intersect($temp, array_filter(explode(",", $v['content'])));
        }
        if(!$temp)
            return [];
        
        
        $rs = Db::name('admin_power')->field("module,controller, actions")->where('id', 'in', $temp)->select();
        $urls = [];
        foreach($rs as $v){
            $t = explode(",", $v['actions']);
            foreach($t as $tv){
                $urls[] = $v['controller']."/".$tv;
            }
        }
        session('deny_urls',$urls);
        return $urls;
    }


    /**
     * 验证是否可能删除
     * @param unknown $id  权限id
     * @return true(可以删除) or false;
     */
    public function checkDel($id){
        $rs = Db::name('admin_user')->where('role_ids', 'like', "%,$id,%")->find();
        if( $rs )
            return com_error(['该部门下已有用户，不能删除!']);
        return true;
    }
}